<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Luo;
use Illuminate\Support\Facades\View;


class AntUserController extends Controller {
    public function __construct() {
        $this->middleware('need_admin_login');

        View::share('luo_list', Luo::all());
    }

    public function users() {
        $conditions = [];
        $status = request()->input('status', -1);
        if($status != -1){
            array_push($conditions, ['status', '=', $status]);
        }
        $users = User::where($conditions)->paginate(20);
        return view('admin.ants.index', ['users' => $users, 'status' => $status]);
    }

    public function query($query) {
        $conditions = [];
        $status = request()->input('status', -1);
        if($status != -1){
            array_push($conditions, ['status', '=', $status]);
        }
        $users = User::where($conditions)->where(function($q) use ($query){
            $q->where("name", "like", "%$query%")
              ->orWhere("email", "like", "%$query%");
        })->paginate(20);
        return view('admin.ants.index', ['users' => $users, 'status' => $status]);
    }

    public function luo_users($name) {
        $luo = Luo::get_by_name($name);
        if(!$luo) abort(404);

        $data = $luo->user_relation_list()->paginate(20);
        foreach($data as $i){
            $users[] = $i->user;
        }
        return view('admin.ants.luo_users', ['data' => $data, 'users' => $users]);
    }

    public function delete($id) {
        $u = User::findOrFail($id);
        $u->delete();
    }

    public function review($id) {
        $u = User::findOrFail($id);

        if(request()->isMethod('post')){
            $luo = Luo::get_by_name(request()->input('luo'));
            if($luo) {
                $u->join($luo);
                return view('admin.ants.review', ['user' => $u, 'msg' => '修改成功!']);
            }
        }
        return view('admin.ants.review', ['user' => $u]);
    }
}
